<?php

namespace app\teacher\controller\v1;

use app\common\controller\BaseController;
use app\common\service\EasyWechatService;
use app\teacher\validate\CreateTeacherValidate;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use app\teacher\model\User as UserModel;
use app\teacher\model\Teacher as TeacherModel;
use app\teacher\model\TeacherImage as TeacherImageModel;
use app\teacher\model\TeacherCourse as TeacherCourseModel;

class User extends BaseController
{
    /**
     * 授权
     */
    public function auth(EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $code = $this->notEmpty('code');
        $res = $easyWechatService->wxappAuth($code);
//        return json($res);
        $token = md5(sha1(time().uniqid().mt_rand(10000, 99999)).$res['openid']);
        $user = UserModel::getByField('wxapp_openid', $res['openid']);
        if ($user) {
            $this->errorMsg(991);
        }
        $teacher = TeacherModel::getByField('wxapp_openid', $res['openid']);
        if (!$teacher || !$teacher->phone) {
            $this->errorMsg(9997, ['wxapp_openid' => $res['openid']]);
        }
        $teacher->token = $token;
        $res = $teacher->save();
        if (!$res) {
            $this->forbidden();
        }
        Cache::set('teacher_token_'.$token, $teacher->teacher_id, 2592000);

        $this->success('', ['teachertoken' => $token]);
    }

    /**
     * 解密
     */
    public function decrypt(EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $openid = $this->notEmpty('wxapp_openid');
        $iv = $this->notEmpty('iv');
        $encryptedData = $this->notEmpty('encryptedData');
        $sessionKey = Cache::get('session_key_'.$openid);
        if (!$sessionKey || strlen($sessionKey) != 24) {
            $this->errorMsg(990);
        }
        if (strlen($iv) != 24) {
            $this->errorMsg(899);
        }
        $aesKey = base64_decode($sessionKey);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $res = json_decode($result, true);
//        $res = $easyWechatService->decryptData($sessionKey, $iv, $encryptedData);
        $res ? $this->success('', $res) : $this->errorMsg(888);
    }


    /**
     * 新增教师
     */
    public function create(CreateTeacherValidate $createTeacherValidate, TeacherModel $teacherModel)
    {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($createTeacherValidate, $data);
        $data['token'] = md5(sha1(time()).$data['wxapp_openid']);
        $teacher = TeacherModel::getByField('phone', $data['phone']);
        $user = UserModel::getByField('mobile', $data['phone']);
        if ($teacher || $user) {
            $this->errorMsg(9993);
        }

        Db::startTrans();
        try {
            //新增教师
            $teacherModel->add($data);
            //图片
            TeacherImageModel::add($teacherModel->teacher_id, $data['images']);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->forbidden() : $this->success('', ['teachertoken' => $teacherModel->token]);
    }

    /**
     * 教师信息
     */
    public function info()
    {
        $teacher = TeacherModel::getTeacher($this->teacherId);
        $this->success('', compact('teacher'));
    }

    /**
     * 账户余额
     */
    public function money()
    {
        $teacher = TeacherModel::field('money, verify')->find($this->teacherId);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        //提现说明
        $teacher['explain'] = getSettingValue('withdraw_explain');
        $this->success('', $teacher);
    }

    /**
     * 开关接单
     */
    public function online()
    {
        $teacherId = $this->teacherId;
        $teacher = TeacherModel::with('teacherCourse')->find($teacherId);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        if (!$teacher->teacher_course) {
            $this->errorMsg(10008);
        }
        if ($teacher->verify < 2) {
            $this->errorMsg(20002);
        }
        Db::startTrans();
        try {
            if ($teacher->online) {
                //关闭接单
                $teacher->online = 0;
                //课程下线
                $data = ['onlineswitch' => 0];
            } else {
                //开启接单
                $teacher->online = 1;
                //课程上线
                $data = ['onlineswitch' => 1];
            }
            $teacher->save();
            TeacherCourseModel::updateByTeacherId($teacherId, $data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->forbidden() : $this->success('');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->isPost();
        $data = $this->request->post();
        $teacherId = $this->teacherId;
        $teacher = TeacherModel::find($teacherId);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        Db::startTrans();
        try {
            if ((isset($data['front_identity']) && $teacher->front_identity != $data['front_identity']) ||
                (isset($data['back_identity']) && $teacher->back_identity != $data['back_identity']) ||
                (isset($data['hand_identity']) && $teacher->hand_identity != $data['hand_identity']))
            {
                //重新审核
                $teacher->verify = 1;
            }
            //更新教师信息
            $teacher->allowField(true)->save($data);
            if (isset($data['images'])) {
                //删除教师图片
                TeacherImageModel::deleteImage($teacherId);
                //添加教师图片
                TeacherImageModel::add($teacherId, $data['images']);
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->forbidden() : $this->success('');
    }

    /**
     * 可语协议
     */
    public function agreement()
    {
        $content = getSettingValue('agreement');
        $this->success('', compact('content'));
    }


}
